import { useState, useEffect } from 'react';
import { Popup, Picker } from 'react-vant';
import './index.less';
import { staticActionList, timeColumn, deviceId } from '../../utils/staticData';

export default function Action({ propsAction }: any) {
  const Hejia = (window as any).Hejia;
  const { isOnline, status, mode, setWorkTime } = propsAction;
  const [visibleStr, setVisibleStr] = useState<String>('');
  const [minsList, setMinsList] = useState<string[]>(['0']);
  const [time, setTime] = useState<number>(setWorkTime);

  const state = {
    timeVisible: 'time'
  };

  useEffect(() => {
    // 设置时间
    setMinsList([`${setWorkTime}`]);
    setTime(setWorkTime);
  }, [setWorkTime]);

  const onClose = () => setVisibleStr('');

  const itemEle = (): JSX.Element => {
    return (
      <div
        className="action-item"
        key={1}
        onClick={() => setVisibleStr('time')}
      >
        <div className="left">
          <div className="title">烹饪时间设置</div>
          <div className="num">{time > 0 ? time + '分钟' : '未设置'}</div>
        </div>
        <i className="iconfont icon-arrow" />
      </div>
    );
  };

  return (
    <div className="action">
      <div className="mask-wapper">
        {/* 不可点击：
          1. 离线
          2. 待机，且没有选中模式
          3. 运行中
         */}
        {(!isOnline ||
          (status === 0 && mode === 0) ||
          [1, 2, 3, 8, 10].includes(mode) ||
          status === 1 ||
          status === 3) && <div className="mask"></div>}
        {itemEle()}
      </div>
      {/* 时间弹框 */}
      <Popup
        round
        visible={state.timeVisible === visibleStr}
        style={{ height: '40%' }}
        position="bottom"
        onClose={onClose}
      >
        <div className="time-wrapper">
          <Picker
            value={minsList}
            title="烹饪时间设置"
            placeholder=""
            confirmButtonText="确定"
            columns={timeColumn()}
            onChange={(val: any): void => {
              setMinsList([val]);
            }}
            onCancel={() => onClose()}
            onConfirm={() => {
              const mins: number = Number(minsList[0]);
              setTime(mins);
              onClose();
              Hejia.setControlParam(
                {
                  // deviceId,
                  parameters: {
                    param: [
                      {
                        name: 'setWorkTime',
                        content: mins
                      }
                    ]
                  }
                },
                function () {
                  // success, no response
                  console.log('success');
                },
                function (msg: string, obj: any) {
                  console.log(msg + obj.resultCode + obj.resultCodeMessage);
                }
              );
            }}
          />
          <div className="unit">分钟</div>
        </div>
      </Popup>
    </div>
  );
}
